<template>
  <div class="properties-table" v-dialog-drag>
    <div class="properties-table-header drag">
      <div class="properties-table-header-left">
        <div class="layer-wrapper">
          <div
            class="layer"
            :class="{
              active: selectedLayerIndex === index
            }"
            v-for="(item, index) in layers"
            :key="item.id"
            @click="handleLayerChange(index)"
          >
            <span class="layer-title">{{
              item.title
            }}</span>
          </div>
        </div>
      </div>

      <div class="properties-table-header-right">
        <i
          class="el-icon-circle-close close"
          @click="close"
        />
      </div>
    </div>

    <div class="properties-table-body">
      <div
        class="properties-table-body-header"
        v-if="dataServiceList.length"
      >
        <div class="properties-table-body-header-left">
          <div class="data-wrapper">
            <div
              class="data"
              :class="{
                active: selectedDataIndex === index
              }"
              v-for="(item, index) in dataServiceList"
              :key="item.pkid"
              @click="handleDataChange(index)"
            >
              <span class="data-title">{{
                item.name
              }}</span>
            </div>
          </div>
        </div>
        <div class="properties-table-body-header-right">
          <div class="filter-wrapper">
            <div
              class="row"
              @click="
                filterPanelVisible = !filterPanelVisible
              "
            >
              <span class="title">条件筛选</span>
              <Icon
                title="筛选"
                :name="
                  filterPanelVisible
                    ? 'shaixuanshouqi'
                    : 'shaixuan'
                "
                font-size="19"
                :color="
                  filterPanelVisible
                    ? 'rgba(-1, 210, 255, 1)'
                    : '#D1E6F0'
                "
              />
            </div>
          </div>

          <!-- 自定义范围 -->
          <el-button
            type="primary"
            size="small"
            @click="handleDrawCustomArea"
            >自定义范围</el-button
          >

          <!-- 导出数据 -->
          <el-button
            type="primary"
            size="small"
            @click="handleExportData"
            >导出数据</el-button
          >
        </div>
      </div>

      <div class="filter-panel" v-if="filterPanelVisible">
        <div class="control">
          <el-button
            type="success"
            size="small"
            icon="el-icon-plus"
            @click="addFilterParam"
            >新增</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="queryByField"
            >查询</el-button
          >
          <el-button size="small" @click="clearFilterParams"
            >清空</el-button
          >
        </div>

        <div class="filter-params">
          <div
            class="filter-params-item"
            v-for="(item, index) in filterParams"
            :key="index"
          >
            <el-input
              property="请输入关键字"
              clearable
              style="width: 300px; margin: 10px 10px 0 0"
              v-model="item.fieldValue"
              size="small"
              popper-class
            >
              <el-select
                v-model="item.field"
                placeholder="选择字段"
                style="width: 120px"
                slot="prepend"
                :popper-append-to-body="true"
                popper-class="legend-layer"
                clearable
              >
                <el-option
                  v-for="(
                    fieldItem, fieldIndex
                  ) in fieldList"
                  :key="fieldIndex"
                  :label="fieldItem"
                  :value="fieldItem"
                ></el-option>
              </el-select>
            </el-input>
          </div>
        </div>
      </div>

      <div class="properties-table-body-content">
        <el-table
          v-if="dataServicePropertyList.length"
          :data="shownDataServicePropertyList"
          style="width: 100%"
          height="256px"
          @row-dblclick="handleTableRowDblClick"
        >
          <el-table-column
            v-for="item in dataServiceKeyList"
            :key="item"
            :prop="item"
            :label="item"
          >
            <template slot-scope="scope">
              <el-tooltip
                effect="dark"
                :content="scope.row[item]"
                placement="top"
              >
                <span>{{ scope.row[item] }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!--        :total="dataServicePropertyUrlList.length"-->
        <el-pagination
          v-if="dataServicePropertyList.length"
          small
          layout="->, prev, pager, next"
          :page-size="pageSize"
          :current-page.sync="pageIndex"
          :total="total"
          @current-change="pageChange"
        />

        <el-empty v-if="total === 0" />
      </div>
    </div>
  </div>
</template>

<script>
import { getAction } from '@/utils/helper'
import axios from 'axios'
import { export_json_to_excel as exportJsonToExcel } from '@/utils/excel/Export2Excel'
import Icon from '@/components/icon'

let _layerManager, _viewer

let customAreaHandlerPolygon

let _previousEntity

export default {
  name: 'PropertiesTable',

  inject: ['viewerId'],

  components: {
    Icon
  },

  data() {
    return {
      layers: [],
      selectedLayerIndex: -1,
      selectedDataIndex: -1,
      total: 0,
      // 数据服务列表
      dataServiceList: [],
      // 数据属性url列表
      dataServicePropertyUrlList: [],
      //
      dataServiceKeyList: [],
      // 数据属性列表
      dataServicePropertyList: [],
      shownDataServicePropertyList: [],
      pageIndex: 1,
      pageSize: 20,
      // field: '',
      fieldList: [],
      // fieldValue: '',
      customArea: false,
      regions: [],
      filterPanelVisible: false,
      filterParams: [],
      isFilterMode: false
    }
  },

  async created() {
    const { layerManager, viewer } = await getAction(
      this.viewerId
    )
    _layerManager = layerManager
    _viewer = viewer

    this.getLayers()
  },

  mounted() {
    this.$bus.$on('changePropertiesTableData', () => {
      this.layers = []
      this.selectedLayerIndex = -1
      this.selectedDataIndex = -1
      this.total = 0
      this.dataServiceList = []
      // this.dataServicePropertyUrlList = []
      this.dataServiceKeyList = []
      this.dataServicePropertyList = []
      this.pageIndex = 1
      // this.field = ''
      this.fieldList = []
      this.customArea = false
      this.regions = []

      this.$nextTick(() => {
        this.getLayers()
      })
    })
  },

  beforeDestroy() {
    if (_previousEntity && _viewer) {
      _viewer.entities.remove(_previousEntity)
    }

    // const currentLayer =
    //   this.layers[this.selectedLayerIndex]
    // if (currentLayer.serviceType === '27') {
    //   currentLayer.layer.forEach((item) => {
    //     item.updateAllObjsVisible &&
    //       item.updateAllObjsVisible(true)
    //   })
    // }

    this.$bus.$off('changePropertiesTableData')
  },

  methods: {
    close() {
      this.$emit('close')
    },

    getLayers() {
      this.layers = _layerManager.layers.reverse()
      // .filter((item) => item.type !== 'layer')
      if (this.layers && this.layers.length) {
        this.selectedLayerIndex = 0
        this.getDataServiceList(0)
      }
    },

    /**
     * 切换图层选项
     *
     * @param {Number} index 图层索引
     */
    handleLayerChange(index) {
      // 定位到当前点击的layer
      // const currentLayer =
      //   this.layers[this.selectedLayerIndex]
      // const { type, layer } = currentLayer
      // switch (type) {
      //   case 'geojson':
      //     _viewer.flyTo(layer)
      //     break
      //   case 'mvt':
      //     const bounds = layer.rectangle
      //     _viewer.scene.camera.setView({
      //       destination: Cesium.Cartesian3.fromRadians(
      //         (bounds.east + bounds.west) * 0.5,
      //         (bounds.north + bounds.south) * 0.5,
      //         10000
      //       )
      //     })
      //     break
      //   case 'imagery':
      //     _viewer.flyTo(layer)
      //     break
      //   case 'layer':
      //     // viewer.camera.flyTo({
      //     //   destination: Cesium.Cartesian3.fromDegrees(layer.lon, layer.lat, 1000)
      //     // })
      //     _viewer.flyTo(layer[0])
      //     break
      //   case 'tileset':
      //     _viewer.flyTo(layer)
      //     break
      //   default:
      //     break
      // }

      if (this.selectedLayerIndex !== index) {
        this.isFilterMode = false

        // const currentLayer =
        //   this.layers[this.selectedLayerIndex]
        // if (currentLayer.serviceType === '27') {
        //   currentLayer.layer.forEach((item) => {
        //     item.updateAllObjsVisible &&
        //       item.updateAllObjsVisible(true)
        //   })
        // }

        this.selectedLayerIndex = index
        this.selectedDataIndex = -1
        // this.dataServicePropertyUrlList = []
        this.dataServiceKeyList = []
        this.dataServicePropertyList = []
        this.shownDataServicePropertyList = []
        this.customArea = false
        this.regions = []
        this.pageIndex = 1
        this.total = 0
        this.filterParams = []
        this.filterPanelVisible = false
        this.getDataServiceList(index)
      }
    },

    /**
     * 切换数据选项
     *
     * @param {Number} index 数据索引
     */
    handleDataChange(index) {
      if (this.selectedDataIndex !== index) {
        this.isFilterMode = false

        // const currentLayer =
        //   this.layers[this.selectedLayerIndex]
        // if (currentLayer.serviceType === '27') {
        //   currentLayer.layer.forEach((item) => {
        //     item.updateAllObjsVisible &&
        //       item.updateAllObjsVisible(true)
        //   })
        // }

        this.selectedDataIndex = index
        this.dataServiceKeyList = []
        this.fieldList = []
        // this.fieldValue = ''
        // this.field = ''
        this.dataServicePropertyList = []
        this.shownDataServicePropertyList = []
        this.customArea = false
        this.regions = []
        this.pageIndex = 1
        this.total = 0
        this.filterParams = []
        this.filterPanelVisible = false
        // this.getPropertyUrlList(index)
        this.getFieldList(index)
      }
    },

    /**
     * 获取数据服务配置列表
     *
     * @param {Number} index 图层索引
     */
    getDataServiceList(index) {
      this.dataServiceList.splice(
        0,
        this.dataServiceList.length
      )
      const currentLayer =
        this.layers[this.selectedLayerIndex]
      console.log(
        '当前服务',
        this.layers[this.selectedLayerIndex]
      )
      if (
        currentLayer.dataList[
          currentLayer.currentDataIndex
        ] &&
        currentLayer.dataList[currentLayer.currentDataIndex]
          .resourceServiceDataInfoList &&
        currentLayer.dataList[currentLayer.currentDataIndex]
          .resourceServiceDataInfoList.length
      ) {
        this.dataServiceList.push(
          ...currentLayer.dataList[
            currentLayer.currentDataIndex
          ].resourceServiceDataInfoList
        )
        this.selectedDataIndex = 0
        // this.getPropertyUrlList(0)
        this.getFieldList(0)
      } else {
        this.$message.warning(
          '未读取到该服务的数据服务配置'
        )
      }
    },

    /**
     * 获取服务属性列表总数
     *
     * @param {Number} index 数据索引
     */
    getPropertyUrlList(index) {
      this.dataServicePropertyUrlList = []
      this.dataServicePropertyList = []
      axios
        .get(
          `${this.dataServiceList[index].serviceDataUrl}/features.json?toIndex=-1`
        )
        .then((res) => {
          if (
            // res.status === 200 &&
            res.data &&
            res.data.childUriList &&
            res.data.childUriList.length
          ) {
            const featureUrlList = []
            res.data.childUriList.forEach((val) => {
              const url = val + '.json'
              featureUrlList.push(url)
            })
            this.dataServicePropertyUrlList = featureUrlList
            this.total = featureUrlList.length
            this.pageIndex = 1
            this.getPropertyListByPageAndUrl()
          }
        })
    },

    // 获取字段列表
    getFieldList(index) {
      axios
        .get(
          `${this.dataServiceList[index].serviceDataUrl}/fields.json`
        )
        .then((res) => {
          // if (res.status === 200 && res.data) {
          if (res.data) {
            this.dataServiceKeyList = res.data.fieldNames
            this.fieldList = this.dataServiceKeyList.filter(
              (e) => e.toLowerCase().indexOf('sm') !== 0
            )
            console.log(this.fieldList)
            this.getPropertyUrlList(this.selectedDataIndex)
            // this.getTableList(
            //   this.selectedDataIndex,
            //   false,
            //   false
            // )
          }
        })
    },

    // 获取数据列表
    getTableList(index, exportData, isFilter) {
      this.dataServicePropertyList = []
      this.shownDataServicePropertyList = []

      const dataService =
        this.dataServiceList[index].serviceDataUrl
      // let fromIndex = 0
      // let toIndex = -1
      // if (!exportData) {
      //   fromIndex = (this.pageIndex - 1) * this.pageSize
      //   toIndex = this.pageIndex * this.pageSize - 1
      // }
      const dataServiceUrl =
        dataService.substring(
          0,
          dataService.lastIndexOf('/datasources/')
        ) +
        // `/featureResults.json?returnContent=true&fromIndex=${fromIndex}&toIndex=${toIndex}`
        '/featureResults.json?returnContent=true&toIndex=-1'
      console.log('请求地址', dataServiceUrl)
      const dataSourceAndDataSet = dataService
        .substring(
          dataService.lastIndexOf('/datasources/') +
            '/datasources/'.length
        )
        .split('/datasets/')
        .map((item) => decodeURI(item))
      // console.log('数据源:数据集', dataSourceAndDataSet)
      const params = this.filterParams.filter(
        (item) => item.field && item.fieldValue
      )
      const filterList = params.map((item) => {
        return `${item.field}='${item.fieldValue}'`
      })
      // console.log('filterList', filterList)
      const sqlParams = filterList.join(' and ')
      // console.log('sqlParams', sqlParams)
      const sqlParameter = {
        datasetNames: [`${dataSourceAndDataSet.join(':')}`],
        getFeatureMode: 'SQL',
        queryParameter: {
          fields: this.dataServiceKeyList,
          // attributeFilter: this.field
          //   ? `${this.field} like '%${this.fieldValue}%'`
          //   : ''
          attributeFilter: sqlParams
        },
        hasGeometry: false
      }
      const queryData = JSON.stringify(sqlParameter)
      this.dataServicePropertyList = []
      axios.post(dataServiceUrl, queryData).then((res) => {
        // console.log('res.data', res.data)
        if (res.data.featureCount > 0) {
          this.total = res.data.totalCount
          // this.dataServicePropertyUrlList = []
          // let list
          // if (exportData) {
          //   list = res.data.features.slice(
          //     (this.pageIndex - 1) * this.pageSize,
          //     this.pageIndex * this.pageSize
          //   )
          // } else {
          //   list = res.data.features
          // }
          const list = res.data.features
          const fieldNames = list[0].fieldNames
          const dataList = []
          // const dataListAll = []
          list.forEach((i) => {
            const fieldValues = i.fieldValues
            const va = {}
            fieldValues.forEach((value, idx) => {
              va[fieldNames[idx]] = value
            })
            // if (i.geometry.center) {
            //   va['geometryCenter'] = i.geometry.center
            //   console.log(
            //     'geometryCenter',
            //     i.geometry.center
            //   )
            // } else if (i.geometry.position) {
            //   va['geometryCenter'] = i.geometry.position
            //   console.log(
            //     'geometryCenter',
            //     i.geometry.position
            //   )
            // }
            dataList.push(va)
          })
          // res.data.features.forEach((i) => {
          //   const fieldValues = i.fieldValues
          //   const va = {}
          //   fieldValues.forEach((value, idx) => {
          //     va[fieldNames[idx]] = value
          //   })
          //   dataListAll.push(va)
          // })
          this.dataServicePropertyList = dataList
          this.shownDataServicePropertyList =
            this.dataServicePropertyList.slice(
              (this.pageIndex - 1) * this.pageSize,
              this.pageIndex * this.pageSize
            )
          // this.dataServicePropertyUrlList = dataListAll

          const currentLayer =
            this.layers[this.selectedLayerIndex]
          // console.log('当前layer', currentLayer)
          if (isFilter) {
            if (this.dataServicePropertyList.length) {
              // console.log('数据变化')
              if (currentLayer.serviceType === '27') {
                // 三维服务
                // console.log('layers', currentLayer.layer)
                const ids = []
                this.dataServicePropertyList.forEach(
                  (item) => {
                    Object.entries(item).forEach(
                      (entries) => {
                        if (
                          entries[0].toLowerCase() ===
                          'smid'
                        ) {
                          ids.push(entries[1])
                        }
                      }
                    )
                  }
                )
                // console.log('过滤ids', ids)
                currentLayer.layer.forEach((item) => {
                  item.setObjsVisible &&
                    item.setObjsVisible(ids, true)
                })
              }
            } else {
              // console.log('数据清空')
              if (currentLayer.serviceType === '27') {
                // 三维服务
                // console.log('layers', currentLayer.layer)
                // currentLayer.layer.forEach((item) => {
                //   item.updateAllObjsVisible &&
                //     item.updateAllObjsVisible(true)
                // })
              }
            }
          } else {
            // console.log('数据清空')
            if (currentLayer.serviceType === '27') {
              // 三维服务
              // console.log('layers', currentLayer.layer)
              // currentLayer.layer.forEach((item) => {
              //   item.updateAllObjsVisible &&
              //     item.updateAllObjsVisible(true)
              // })
            }
          }
          if (exportData) {
            const dataListAll = []
            res.data.features.forEach((i) => {
              const fieldValues = i.fieldValues
              const va = {}
              fieldValues.forEach((value, idx) => {
                va[fieldNames[idx]] = value
              })
              dataListAll.push(va)
            })
            const tHeader = this.dataServiceKeyList // 设置Excel的表格第一行的标题
            const filterVal = this.dataServiceKeyList // 对象tableData中一个对象的属性
            // const list = this.dataServicePropertyUrlList // 把data里的tableData存到list
            const list = dataListAll // 把data里的tableData存到list
            const data = this.formatJson(filterVal, list) // 对数据过滤
            const head =
              this.dataServiceList[this.selectedLayerIndex]
                .name +
              // (this.field
              //   ? this.field + '类似于' + this.fieldValue
              //   : '') +
              '属性信息列表'
            // tHeader：第一行标题； data:要显示的数据；head：下载的文件名
            exportJsonToExcel(tHeader, data, head)
          }
        }
      })
    },

    /**
     * 根据自定义范围统计数据
     *
     * @param index 数据服务索引
     * @param regions 范围坐标点
     * @param exportData 是否导出数据
     */
    getTableListByCustomArea(index, regions, exportData) {
      this.dataServicePropertyList = []
      this.shownDataServicePropertyList = []

      const dataService =
        this.dataServiceList[index].serviceDataUrl
      const dataServiceUrl = dataService.substring(
        0,
        dataService.lastIndexOf('/datasources/')
      )
      console.log('请求地址', dataServiceUrl)
      const dataSourceAndDataSet = dataService
        .substring(
          dataService.lastIndexOf('/datasources/') +
            '/datasources/'.length
        )
        .split('/datasets/')
        .map((item) => decodeURI(item))

      const polygon = L.polygon([...regions, regions[0]])
      console.log('polygon', polygon)
      // let fromIndex = 0
      // let toIndex = -1
      // if (!exportData) {
      //   fromIndex = (this.pageIndex - 1) * this.pageSize
      //   toIndex = this.pageIndex * this.pageSize - 1
      // }
      const params = this.filterParams.filter(
        (item) => item.field && item.fieldValue
      )
      const filterList = params.map((item) => {
        return `${item.field}='${item.fieldValue}'`
      })
      // console.log('filterList', filterList)
      const sqlParams = filterList.join(' and ')
      // console.log('sqlParams', sqlParams)
      const param =
        new SuperMap.GetFeaturesByGeometryParameters({
          datasetNames: [
            `${dataSourceAndDataSet.join(':')}`
          ],
          geometry: polygon,
          spatialQueryMode:
            SuperMap.SpatialQueryMode.INTERSECT,
          // fromIndex: fromIndex,
          // toIndex: toIndex,
          toIndex: -1,
          // attributeFilter: this.field
          //   ? `${this.field} like '%${this.fieldValue}%'`
          //   : '',
          attributeFilter: sqlParams,
          hasGeometry: false
        })
      L.supermap
        .featureService(dataServiceUrl)
        .getFeaturesByGeometry(param, (result) => {
          if (result.error) {
            this.$message.error(
              result.error.errorMsg || '范围查询失败'
            )
          }
          if (result.result.featureCount > 0) {
            this.total = result.result.totalCount
            // this.dataServicePropertyUrlList = []
            this.dataServiceKeyList = []
            // const list = result.result.features.features
            //   .slice(
            //     (this.pageIndex - 1) * this.pageSize,
            //     this.pageIndex * this.pageSize
            //   )
            //   .map((item) => item.properties)
            // let list
            // if (exportData) {
            //   list = result.result.features.features.slice(
            //     (this.pageIndex - 1) * this.pageSize,
            //     this.pageIndex * this.pageSize
            //   )
            //   // .map((item) => item.properties)
            // } else {
            //   list = result.result.features.features
            // }
            const list = result.result.features.features
            const fieldNames = Object.keys(
              list[0].properties
            )
            this.dataServiceKeyList.push(...fieldNames)
            const dataList = []
            // const dataListAll = []
            list.forEach((i) => {
              const fieldValues = Object.values(
                i.properties
              )
              const va = {}
              fieldValues.forEach((value, idx) => {
                va[fieldNames[idx]] = value
              })
              // switch (i.geometry.type) {
              //   case 'Point':
              //     va['geometryCenter'] = {
              //       x: i.geometry.coordinates[0],
              //       y: i.geometry.coordinates[1]
              //     }
              //     break
              //   case 'LineString':
              //     va['geometryCenter'] = {
              //       x: i.geometry.coordinates[0][0],
              //       y: i.geometry.coordinates[0][1]
              //     }
              //     break
              //   case 'Polygon':
              //     va['geometryCenter'] = {
              //       x: i.geometry.coordinates[0][0][0],
              //       y: i.geometry.coordinates[0][0][1]
              //     }
              //     break
              //   default:
              //     break
              // }
              dataList.push(va)
            })
            // result.result.features.features.forEach((i) => {
            //   const fieldValues = Object.values(i)
            //   const va = {}
            //   fieldValues.forEach((value, idx) => {
            //     va[fieldNames[idx]] = value
            //   })
            //   dataListAll.push(va)
            // })
            this.dataServicePropertyList = dataList
            this.shownDataServicePropertyList =
              this.dataServicePropertyList.slice(
                (this.pageIndex - 1) * this.pageSize,
                this.pageIndex * this.pageSize
              )
            console.log(
              'dataServicePropertyList',
              this.dataServicePropertyList
            )
            // this.dataServicePropertyUrlList = dataListAll
            if (exportData) {
              const dataListAll = []
              result.result.features.features.forEach(
                (i) => {
                  const fieldValues = Object.values(
                    i.properties
                  )
                  const va = {}
                  fieldValues.forEach((value, idx) => {
                    va[fieldNames[idx]] = value
                  })
                  dataListAll.push(va)
                }
              )
              const tHeader = this.dataServiceKeyList // 设置Excel的表格第一行的标题
              const filterVal = this.dataServiceKeyList // 对象tableData中一个对象的属性
              // const list = this.dataServicePropertyUrlList // 把data里的tableData存到list
              const list = dataListAll // 把data里的tableData存到list
              const data = this.formatJson(filterVal, list) // 对数据过滤
              const head =
                this.dataServiceList[
                  this.selectedLayerIndex
                ].name +
                // (this.field
                //   ? this.field + '类似于' + this.fieldValue
                //   : '') +
                '属性信息列表'
              // tHeader：第一行标题； data:要显示的数据；head：下载的文件名
              exportJsonToExcel(tHeader, data, head)
            }
          }
        })
    },

    /**
     * 根据分页参数和json的url地址获取服务属性列表，用于在没有筛选条件和自定义区域时查询
     */
    getPropertyListByPageAndUrl() {
      this.dataServicePropertyList = []
      this.shownDataServicePropertyList = []
      const urlList = this.dataServicePropertyUrlList.slice(
        (this.pageIndex - 1) * this.pageSize,
        this.pageIndex * this.pageSize
      )
      Promise.all([
        ...urlList.map((item) =>
          axios.get(item + '?hasGeometry=false')
        )
      ]).then((item) => {
        const fieldNames = item[0].data.fieldNames
        const propertyList = []
        fieldNames.forEach((fieldName) => {
          propertyList.push({
            label: fieldName,
            value: fieldName
          })
        })
        const dataList = []
        item.forEach((i) => {
          const fieldValues = i.data.fieldValues
          const va = {}
          fieldValues.forEach((value, idx) => {
            // va[fieldNames[idx]] = value
            // 通过fields.json获取到的属性名与实际查询到的属性名大小写可能不一致，通过表格列名的值来命名
            va[this.dataServiceKeyList[idx]] = value
          })
          dataList.push(va)
        })
        if (!this.dataServiceKeyList.length) {
          this.dataServiceKeyList.push(
            ...Object.keys(dataList[0])
          )
        }
        this.dataServicePropertyList = dataList
        this.shownDataServicePropertyList = dataList
      })
    },

    pageChange(page) {
      this.pageIndex = page
      if (!this.isFilterMode) {
        this.getPropertyListByPageAndUrl()
      } else {
        this.shownDataServicePropertyList =
          this.dataServicePropertyList.slice(
            (this.pageIndex - 1) * this.pageSize,
            this.pageIndex * this.pageSize
          )
      }
    },

    /**
     * 自定义范围绘制
     */
    handleDrawCustomArea() {
      if (!customAreaHandlerPolygon) {
        this.$bus.$emit('customAreaDrawActived', true)
        customAreaHandlerPolygon = new Cesium.DrawHandler(
          _viewer,
          Cesium.DrawMode.Polygon,
          Cesium.ClampMode.Space
        )
        customAreaHandlerPolygon.activeEvt.addEventListener(
          (isActive) => {
            if (isActive === true) {
              _viewer.enableCursorStyle = false
              _viewer._element.style.cursor = ''
            } else {
              _viewer.enableCursorStyle = true
            }
          }
        )
        customAreaHandlerPolygon.drawEvt.addEventListener(
          (result) => {
            customAreaHandlerPolygon.polygon.show = true
            customAreaHandlerPolygon.polyline.show = true
            const regions = []
            for (const pt of result.object.positions) {
              const cartographic =
                Cesium.Cartographic.fromCartesian(pt)
              const longitude = Cesium.Math.toDegrees(
                cartographic.longitude
              )
              const latitude = Cesium.Math.toDegrees(
                cartographic.latitude
              )
              regions.push([latitude, longitude])
            }
            this.regions = regions
            this.$bus.$emit('customAreaDrawActived', false)
            customAreaHandlerPolygon.clear()
            customAreaHandlerPolygon.deactivate()
            customAreaHandlerPolygon = null
            this.customArea = true
            this.pageIndex = 1
            this.isFilterMode = true
            this.getTableListByCustomArea(
              this.selectedDataIndex,
              this.regions
            )
          }
        )
        customAreaHandlerPolygon.activate()
      } else {
        this.$bus.$emit('customAreaDrawActived', false)
        customAreaHandlerPolygon.clear()
        customAreaHandlerPolygon.deactivate()
        customAreaHandlerPolygon = null
      }
    },

    /**
     * 导出数据
     */
    handleExportData() {
      if (this.customArea) {
        this.getTableListByCustomArea(
          this.selectedDataIndex,
          this.regions,
          true
        )
      } else {
        // 无过滤条件导出全部数据excel
        this.getTableList(
          this.selectedDataIndex,
          true,
          false
        )
      }
    },

    /**
     * 新增查询条件
     */
    addFilterParam() {
      this.filterParams.push({
        field: '',
        fieldValue: ''
      })
    },

    /**
     * 确定查询条件
     */
    queryByField() {
      this.isFilterMode = true
      this.pageIndex = 1
      this.getTableList(this.selectedDataIndex, false, true)
    },

    /**
     * 清空查询条件
     */
    clearFilterParams() {
      this.isFilterMode = false
      this.filterParams = []
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]))
    },

    handleTableRowDblClick(row) {
      let smid = ''
      Object.entries(row).forEach((entries) => {
        if (entries[0].toLowerCase() === 'smid') {
          smid = entries[1]
        }
      })
      // console.log('查询smid', smid)
      const dataService =
        this.dataServiceList[this.selectedDataIndex]
          .serviceDataUrl
      const dataServiceUrl =
        dataService.substring(
          0,
          dataService.lastIndexOf('/datasources/')
        ) +
        '/featureResults.json?returnContent=true&toIndex=-1'
      const dataSourceAndDataSet = dataService
        .substring(
          dataService.lastIndexOf('/datasources/') +
            '/datasources/'.length
        )
        .split('/datasets/')
        .map((item) => decodeURI(item))
      const sqlParameter = {
        datasetNames: [`${dataSourceAndDataSet.join(':')}`],
        getFeatureMode: 'SQL',
        queryParameter: {
          fields: [],
          attributeFilter: `smid="${smid}"`
        },
        hasGeometry: true
      }
      const queryData = JSON.stringify(sqlParameter)
      axios.post(dataServiceUrl, queryData).then((res) => {
        if (res.data.featureCount === 1) {
          const geometry = res.data.features[0].geometry
          if (geometry) {
            if (_previousEntity) {
              _viewer.entities.remove(_previousEntity)
            }
            console.log('geometry', geometry)
            if (geometry.center) {
              const center = geometry.center
              _viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(
                  center.x,
                  center.y,
                  3000
                )
              })
              switch (geometry.type) {
                case 'POINT':
                  _previousEntity = new Cesium.Entity({
                    position: Cesium.Cartesian3.fromDegrees(
                      center.x,
                      center.y
                    ),
                    point: {
                      color: Cesium.Color.RED,
                      pixelSize: 5,
                      outlineColor: Cesium.Color.WHITE,
                      outlineWidth: 2,
                      heightReference:
                        Cesium.HeightReference
                          .RELATIVE_TO_GROUND
                    },
                    classificationType:
                      Cesium.ClassificationType.BOTH
                  })
                  _viewer.entities.add(_previousEntity)
                  break
                case 'LINE':
                  _previousEntity = new Cesium.Entity({
                    polyline: {
                      positions: geometry.points.map(
                        (point) =>
                          Cesium.Cartesian3.fromDegrees(
                            point.x,
                            point.y
                          )
                      ),
                      width: 2,
                      material: Cesium.Color.YELLOW
                    },
                    classificationType:
                      Cesium.ClassificationType.BOTH
                  })
                  _viewer.entities.add(_previousEntity)
                  break
                case 'REGION':
                  _previousEntity = new Cesium.Entity({
                    polygon: {
                      hierarchy:
                        Cesium.Cartesian3.fromDegreesArray(
                          geometry.points
                            .map((point) => {
                              return [point.x, point.y]
                            })
                            .flat()
                        ),
                      height: 0,
                      extrudedHeight: 0,
                      material:
                        Cesium.Color.YELLOW.withAlpha(0.5),
                      outline: true,
                      outlineColor: Cesium.Color.YELLOW,
                      heightReference:
                        Cesium.HeightReference
                          .RELATIVE_TO_GROUND
                    },
                    classificationType:
                      Cesium.ClassificationType.BOTH
                  })
                  _viewer.entities.add(_previousEntity)
                  break
                default:
                  break
              }
            } else if (geometry.position) {
              const center = geometry.position
              _viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(
                  center.x,
                  center.y,
                  3000
                )
              })
              const currentLayer =
                this.layers[this.selectedLayerIndex]
              if (currentLayer.serviceType === '27') {
                currentLayer.layer.forEach((item) => {
                  item.setSelection([
                    res.data.features[0].ID
                  ])
                })
              }
            } else if (geometry.type) {
              // let center
              // switch (geometry.type) {
              //   case 'Point':
              //     center = {
              //       x: geometry.coordinates[0],
              //       y: geometry.coordinates[1]
              //     }
              //     break
              //   case 'LineString':
              //     center = {
              //       x: geometry.coordinates[0][0],
              //       y: geometry.coordinates[0][1]
              //     }
              //     break
              //   case 'Polygon':
              //     center = {
              //       x: geometry.coordinates[0][0][0],
              //       y: geometry.coordinates[0][0][1]
              //     }
              //     break
              //   default:
              //     break
              // }
              // if (center) {
              //   _viewer.camera.flyTo({
              //     destination:
              //       Cesium.Cartesian3.fromDegrees(
              //         center.x,
              //         center.y,
              //         500
              //       )
              //   })
              // }
            }
          }
        }
      })
    }
  },

  watch: {
    isFilterMode(val) {
      console.log('过滤模式:', val)
    }
  }
}
</script>

<style lang="scss" scoped>
.properties-table {
  height: 700px;
  width: 1000px;
  box-shadow: 0 0 8px 0 #057595;
  border-radius: 8px;
  background-color: #0b2b41;
  display: flex;
  flex-direction: column;

  &-header {
    height: 40px;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    background-color: #021b2b;
    display: flex;
    align-items: center;

    &-left {
      flex: 1;
      height: 100%;

      .layer-wrapper {
        height: 100%;
        display: flex;
        align-items: center;
      }

      .layer {
        height: 100%;
        padding: 0 10px;
        display: inline-flex;
        align-items: center;
        background-color: #2e5670;
        cursor: pointer;

        &.active {
          background-color: inherit;
        }

        &-title {
          font-size: 14px;
          font-weight: 700;
          color: white;
        }
      }
    }

    &-right {
      .close {
        padding: 10px;
        cursor: pointer;
      }
    }
  }

  &-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    &-header {
      display: flex;
      align-items: flex-start;

      &-left {
        flex: 1;
        margin-top: 18px;

        .data-wrapper {
          height: 100%;
          display: flex;
          align-items: center;
        }

        .data {
          height: 100%;
          padding: 0 10px;
          display: inline-flex;
          align-items: center;
          cursor: pointer;
          color: white;

          &:not(:last-child) {
            border-right: 1px solid #00baff;
          }

          &-title {
            font-size: 14px;
            font-weight: 700;
          }

          &.active {
            color: #00baff;
          }
        }
      }

      &-right {
        padding: 10px;
        display: flex;
        align-items: flex-start;

        .filter-wrapper {
          position: relative;
          display: flex;
          flex-direction: column;
          margin-top: 2px;
          margin-right: 10px;

          .row {
            align-self: flex-end;
            display: flex;
            align-items: center;
            cursor: pointer;

            span.title {
              color: white;
              font-size: 14px;
              line-height: 14px;
            }
          }
        }

        ::v-deep {
          .el-input {
            .el-input-group__prepend {
              background-color: rgba(255, 255, 255, 0.4);
              border-color: rgba(255, 255, 255, 0.4);
            }
          }

          .el-input__inner {
            background-color: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.4);
            color: #d2e6f0;
          }
        }
      }
    }

    .filter-panel {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      padding: 0 10px;

      .control {
        margin-top: 10px;
        align-self: flex-start;
        display: flex;
        align-items: center;
      }

      .filter-params {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        ::v-deep {
          .el-input {
            .el-input-group__prepend {
              background-color: rgba(255, 255, 255, 0.4);
              border: none;
              //border-color: rgba(255, 255, 255, 0.4);
            }
          }

          .el-input__inner {
            background-color: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.4);
            color: #d2e6f0;
          }
        }
      }
    }

    &-content {
      overflow: hidden;
      flex: 1;
      padding: 10px;
      display: flex;
      flex-direction: column;

      ::v-deep {
        .el-table {
          flex: 1;
          background: rgba(255, 255, 255, 0) !important;
          border: 1px solid #007095;

          tr {
            background: rgba(255, 255, 255, 0) !important;
          }

          thead {
            background: linear-gradient(
              90deg,
              rgba(2, 27, 43, 1),
              rgba(25, 47, 61, 1)
            );

            .el-table__cell {
              border-bottom: none;
              padding: 8px 0 !important;
            }

            .el-checkbox {
              display: none;
            }

            .herderName {
              background: rgba(255, 255, 255, 0) !important;
              font-size: 14px;

              .cell {
                font-weight: 400 !important;
                color: #d2e6f0 !important;
                padding-left: 5px !important;
                font-size: 14px !important;
                padding-right: 5px !important;
              }
            }
          }

          .el-table__header-wrapper {
            .el-table__header {
              .has-gutter {
                tr {
                  .el-table__cell {
                    background-color: transparent;
                  }
                }
              }
            }
          }

          .el-table__body {
            background: rgba(255, 255, 255, 0) !important;

            &-wrapper {
              &::-webkit-scrollbar-track {
                background-color: grey;
              }

              &::-webkit-scrollbar-corner {
                background-color: grey;
              }

              &::-webkit-scrollbar-thumb {
                background-color: #007095;
              }
            }

            .el-table__cell {
              border-color: rgba(
                255,
                255,
                255,
                0.2
              ) !important;
              color: #ffffff !important;
              padding-top: 5px;
              padding-bottom: 5px;
            }
          }

          // 鼠标滑过td上作用的样式，ie6不支持:hover伪类属性，如果是ie6要写成tr.over样式
          tr:hover > td {
            background-color: transparent !important;
          }

          tbody {
            .el-checkbox__inner {
              background-color: rgba(255, 255, 255, 0.3);
            }

            .className {
              .cell {
                text-align: left !important;
              }
            }
            .cell {
              font-size: 12px;
              line-height: 21px;
              font-weight: 400;
              padding-left: 5px;
              padding-right: 0;
              color: #ffffff;

              span {
                width: 100px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
            }
          }
        }

        .el-table::before {
          background: none !important;
        }

        .gutter {
          background: rgba(25, 47, 61, 1) !important;
        }
      }

      ::v-deep {
        .el-pagination {
          padding: 10px 0 0 0;

          button {
            background: transparent;
            color: grey;

            &:disabled {
              &:hover {
                color: grey;
              }
            }

            &:hover {
              color: #00d2ff;
            }
          }

          li {
            background-color: transparent;
            color: grey;

            &.active {
              color: white;
            }
          }
        }
      }
    }
  }
}
</style>
